# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response

from rest_framework.views import APIView
from libs.yuntongxun.sms import CCP
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection


from . import contants
from django.http import HttpResponse
class RegisterImageCodeAPIView(APIView):

    def get(self,request,image_code_id):
        text,image = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')

        redis_conn.setex('img_%s'%image_code_id,contants.IMAGECODEEXPIRE,text)

        return HttpResponse(image,content_type='image/jpeg')


from .serializers import RegisterSmsCodeSerializer
from rest_framework.generics import GenericAPIView
class RegisterSmsCodeAPIView(APIView):

    serializer_class = RegisterSmsCodeSerializer

    def get(self,request,mobile):
        query_params = request.query_params

        # text = query_params.get('text')
        # image_code_id=query_params.get('image_code_id')

        serializer = RegisterSmsCodeSerializer(data=query_params)
        serializer.is_valid(raise_exception=True)

        from random import randint
        sms_code = '%06d'%randint(0,999999)

        #CCP().send_template_sms(mobile,[sms_code,5],1)

        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile,sms_code)

        redis_conn = get_redis_connection('code')

        redis_conn.setex('sms_%s'%mobile,300,sms_code)
        return Response({'msg':'ok'})






